<template>
  <ContentWrap>
    <h2 class="fonts24 fontw500">组织架构</h2>
    <ElButton type="primary" :icon="Plus" @click="onAdd">
      {{ t('添加部门') }}
    </ElButton>
    <Table :rowStyle="rowStyle" :headerCellStyle="headerCellStyle" :columns="columns" :data="dataList" row-key="id"
      :loading="loading" sortable @register="tableRegister" />
  </ContentWrap>
  <!-- 删除框 -->
  <Adetele :title="state.deteleTitle" @deteleClick="deteleClick" :deteleBool="state.deteleBool" />
  <Dialog v-model="dialogVisible1" :title="state.dialogVisible1title" width="500">
    <el-form ref="ruleFormRef" :model="state.ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
      status-icon>
      <el-form-item label="部门名称" prop="deptName">
        <el-input v-model="state.ruleForm.deptName" placeholder="请输入部门名称" />
      </el-form-item>
      <el-form-item label="上级部门" prop="">
        <el-cascader :disabled="state.titleNumber == 2" v-model="state.ruleForm.parentId" :options="state.options"
          :props="props1"  />
      </el-form-item>
      <el-form-item label="部门序号" prop="orderNum">
        <!-- <el-input v-model="state.ruleForm.title" placeholder="请输入部门编号" /> -->
        <el-input-number  v-model="state.ruleForm.orderNum" placeholder="请输入部门序号" />
      </el-form-item>

    </el-form>
    <template #footer>
      <div class="flex ">
        <ElButton @click="resetForm(ruleFormRef)">{{ t('dialogDemo.cancel') }}</ElButton>
        <ElButton type="primary" :loading="loadingAdd" @click="submitForm(ruleFormRef)">{{ t('dialogDemo.sure') }}
        </ElButton>
      </div>
    </template>
  </Dialog>
</template>
  
<script setup lang="tsx">
// import { propTypes } from '@/utils/propTypes'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { ContentWrap } from '@/components/ContentWrap'
import { Plus } from '@element-plus/icons-vue'
import { Table, TableColumn, TableSlotDefault } from '@/components/Table'
import { reactive, unref, ref } from 'vue'
import { ElTag, ElButton, ElMessage } from 'element-plus'
import { useTable } from '@/hooks/web/useTable'
import { Adetele } from "../Components/Adetele/index"
import { deptList,deptAdd,deptEdit ,deptDelete,deptTreeList} from "@/api/organizational/index"
const dialogVisible1 = ref(false)
const props1 = {
  checkStrictly: true,
  value: "id",
  label: "label",
  emitPath:false
}
const state = reactive({
  dialogVisible1title: "",
  deteleData: {} as any,
  deteleBool: false,
  deteleTitle: "",
  reactBoolean: false,//重置
  password: "",
  ruleForm: {} as any,
  options: [] as any,//
  titleNumber: 0,
  delId: ""
})
const deteleClick = (val: any) => {
  console.log("父组件", val);
  if (state.deteleTitle == "确认删除部门？") {
    if (val) {
      delApi(state.delId)
      state.deteleBool = false
      return
    } else {
      state.deteleBool = false
    }
  }
  if (state.deteleTitle == "确认重置账号密码？") {
    if (val) {
      state.deteleTitle = "系统已将密码重置为"
      state.reactBoolean = true
    }
    return
  } else if (state.deteleTitle == "系统已将密码重置为") {
    state.reactBoolean = false
    return
  }
}
state.deteleBool = false
// const props = defineProps({
//     data: {
//         type: Array,
//             default: () => []
//     },
// })

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    // const { currentPage, pageSize } = tableState
    const res = await deptTreeList()
    console.log(res);
    state.options = res.data.tree
    return {
      list: res.data.tree
    }
  }
})
const { getList, getElTableExpose, delList } = tableMethods
getList()
const { loading, dataList, total, currentPage, pageSize } = tableState
const headerCellStyle: any = {
  "background": "#F2F6FC",
  "height": "48px"
}
const rowStyle: any = {
  "height": "48px"
}
const { t } = useI18n()
const columns = reactive<TableColumn[]>([
  {
    field: 'label',
    label: t('层级')
  },
  {
    field: 'action',
    label: t('tableDemo.action'),
    width: 251,
    slots: {
      default: (data) => {
        return (
          <>
            <ElButton type="primary" link onClick={() => actionFn(data)}>
              {t('编辑')}
            </ElButton>
            <ElButton type="danger" link onClick={() => delData(data)}>
              {t('tableDemo.detele')}
            </ElButton>
            <ElButton type="primary" link onClick={() => receat(data)}>
              {t('tableDemo.add')}
            </ElButton>
          </>


        )
      }
    }
  }
])
const delData = (row: any) => {
  console.log("删除", row);
  state.delId = row[0].row.id
  state.deteleTitle = "确认删除部门？"
  state.deteleBool = true
}
const receat = (data: any) => {
  state.ruleForm = {} as any
  console.log("添加", data[0].row);
  dialogVisible1.value = true
  state.ruleForm.parentId=data[0].row.id
  state.dialogVisible1title = t('添加部门')
  state.titleNumber = 2
  state.ruleForm.orderNum=0
}
const actionFn = (data: TableSlotDefault) => {
  console.log(data[0].row)
  // state.ruleForm = data[0].row
  state.ruleForm.orderNum=data[0].row.weight
  state.ruleForm.deptName=data[0].row.label
  state.ruleForm.parentId=data[0].row.parentId
  state.ruleForm.deptId=data[0].row.id
  dialogVisible1.value = true
  state.dialogVisible1title = t('编辑部门')
  state.titleNumber = 1
}
const onAdd = () => {
  state.ruleForm = {}
  console.log("新增");
  dialogVisible1.value = true
  state.dialogVisible1title = t('添加部门')
  state.titleNumber = 0
  state.ruleForm.parentId=state.options[0].id
  state.ruleForm.orderNum=0
}





// 


// 校验规则
interface RuleForm {
  title: string
  parent_id: string
  pop_id: Number
}
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules<RuleForm>>({
  deptName: [
    { required: true, message: '请输入部门名称', trigger: 'blur' },
    { min: 1, max: 50, message: '请输入1~50个字符', trigger: 'blur' },
  ],
  parent_id: [
    { required: true, message: '请选择上级部门', trigger: 'blur' },
  ],
  orderNum: [
    { required: true, message: '请输入部门序号', trigger: 'blur' },
  ]
})
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log(state.ruleForm);
      if(state.dialogVisible1title =='添加部门'){
        addApi(state.ruleForm)
      }else{
        editApi(state.ruleForm)
      }
      console.log('submit!')
    } else {
      console.log('error submit!', fields)
    }
  })
}
const resetForm = (formEl: FormInstance | undefined) => {
  dialogVisible1.value = false
  if (!formEl) return
  formEl.resetFields()
}
const loadingAdd = ref(false)
const addApi = async (params) => {
  loadingAdd.value = true
  await deptAdd(params).then((res: any) => {
    if (res.code == 200) {
      console.log("保存", res);
      dialogVisible1.value = false
      loadingAdd.value = false
      getList()
      ElMessage.success(res.msg)
    } else {
      loadingAdd.value = false
    }
  }).catch((res:any) => {
    ElMessage.error(res.msg)
    loadingAdd.value = false
  })
}
const editApi = async (params) => {
  loadingAdd.value = true
  await deptEdit(params).then((res: any) => {
    if (res.code == 200) {
      console.log("保存", res);
      dialogVisible1.value = false
      loadingAdd.value = false
      getList()
      ElMessage.success(res.msg)
    }
  }).catch((res:any) => {
    loadingAdd.value = false
    ElMessage.error(res.msg)

  })
}
const delApi = async (params) => {
  loadingAdd.value = true
  await deptDelete(params).then((res: any) => {
    console.log("删除", res);
    dialogVisible1.value = false
    loadingAdd.value = false
    getList()
    ElMessage.success(res.msg)

  }).catch((res:any) => {
    dialogVisible1.value = false
    loadingAdd.value = false
    ElMessage.error(res.msg)
  })
}
</script>
  
<style lang="less" scoped>
.el-button {
  margin-top: 10px;
  margin-bottom: 16px;
}

h2 {
  position: relative;
  margin: 0;
  margin-bottom: 26px;

  &::after {
    position: absolute;
    left: -20px;
    top: 2px;
    content: "";
    width: 8px;
    height: 24px;
    background: #2F6CBC;
    border-radius: 0px 4px 4px 0px;
    opacity: 1;
  }
}
</style>